package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sun.jna.ptr.IntByReference;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.LinePasswordEntity;
import io.renren.modules.sys.entity.LineQcodeEntity;
import io.renren.modules.sys.service.LinePasswordService;
import io.renren.modules.sys.service.LineQcodeService;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


/**
 * 线充二维码
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-10-12 16:59:44
 */
@RestController
@RequestMapping("sys/lineqcode")
public class LineQcodeController {
    @Autowired
    private LineQcodeService lineQcodeService;
    @Autowired
    private LinePasswordService linePasswordService;
    @Value("${web.upload-path}")
    private  String path;
    @Value("${webDownLoad.upload-path}")
    private  String pathDownLoad;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:lineqcode:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = lineQcodeService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 上传
     */
//    @RequestMapping("/saveUpload")
//    public R saveUpload(MultipartFile files) throws Exception {
//        System.out.println(111111);
//        if (files.isEmpty()) {
//            throw new RRException("导入文件不能为空");
//        }
//
//        Workbook workbook = null;
//        int totalNum = 0;
//        String sn = RandomUtil.generateString(16);
//        String path =  "C:\\" + sn+".xlsx";
//        File file = new File(path);
//        //获取到multipartFile文件输入流
//        InputStream input = files.getInputStream();
//        //FileCopyUtils.copy(multipartFile.getBytes(), file);
//        workbook = WorkbookFactory.create(input);
//        List<LineQcodeEntity> list = new ArrayList<LineQcodeEntity>();
////        List<LinePasswordEntity> linePassList = new ArrayList<LinePasswordEntity>();
//        /*遍历sheet页*/
//        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
//            Sheet sheet = workbook.getSheetAt(i);
//            if (sheet == null) {
//                continue;
//            }
//            /*统计导入的总条数，要是你的excell包含了表头，就不用加1了*/
//            if (sheet.getLastRowNum() > 0) {
//                totalNum += sheet.getLastRowNum();
//            }
//            /*遍历行，这里j的初始值取1是因为我的表格里第一行是表头*/
//            for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
//                Row row = sheet.getRow(j);
//                /*解析列，下标从0开始*/
//                Cell cell1 = row.getCell(0);
//                Cell cell2 = row.getCell(1);
//
//                if (cell1 == null||"".equals(cell1)) {
//                    continue;
//                }
//                DecimalFormat df = new DecimalFormat("#");
//                LineQcodeEntity entity = new LineQcodeEntity();
//                LinePasswordEntity linePasswordEntity = new LinePasswordEntity();
//                entity.setSn(cell1.toString());
//                entity.setQcode(cell2.toString());
//                list.add(entity);
//
////                linePassList.add(linePassList);
//                lineQcodeService.saveOrUpdate(entity);
//                LineQcodeEntity lineQcodeEntity = lineQcodeService.getById(entity.getId());
//                linePasswordEntity.setDevicesn("XC01"+lineQcodeEntity.getSn());
//                linePasswordEntity.setQcodeid(lineQcodeEntity.getId());
//                linePasswordService.save(linePasswordEntity);
//            }
//            /*持久化：批量新增*/
////            lineQcodeService.saveBatch(list);
////            linePasswordService.saveBatch(linePassList);
//        }
//        /*解析完删除此路径下的文件*/
//
//        file.delete();
//
//        return R.ok();
//    }

    /**
     * 上传
     */
    @RequestMapping("/saveUpload")
    public R saveUpload(MultipartFile files) throws Exception {
        System.out.println(111111);
        if (files.isEmpty()) {
            throw new RRException("导入文件不能为空");
        }

        Workbook workbook = null;
        int totalNum = 0;
        String sn = RandomUtil.generateString(16);
        String path =  "C:\\" + sn+".xlsx";
        File file = new File(path);
        //获取到multipartFile文件输入流
        InputStream input = files.getInputStream();
        //FileCopyUtils.copy(multipartFile.getBytes(), file);
        workbook = WorkbookFactory.create(input);

        /*遍历sheet页*/
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            /*统计导入的总条数，要是你的excell包含了表头，就不用加1了*/
            if (sheet.getLastRowNum() > 0) {
                totalNum += sheet.getLastRowNum();
            }
            /*遍历行，这里j的初始值取1是因为我的表格里第一行是表头*/
            for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
                Row row = sheet.getRow(j);
                /*解析列，下标从0开始*/
                Cell cell1 = row.getCell(0);
                Cell cell2 = row.getCell(1);

                if (cell1 == null||"".equals(cell1)) {
                    break;
                }
                List<LineQcodeEntity> lists = lineQcodeService.getLineCode(cell2.toString());
                if(lists!=null && lists.size()>0){
                    LineQcodeEntity entity = lists.get(0);
                    entity.setSn(cell1.toString());
                    lineQcodeService.saveOrUpdate(entity);//绑定line_code表序列号


                    LinePasswordEntity linePasswordEntity = new LinePasswordEntity();
                    linePasswordEntity.setDevicesn("XC01"+cell1.toString());
                    linePasswordEntity.setQcodeid(entity.getId());
                    linePasswordService.save(linePasswordEntity);
                    //list.add(entity);


                }

            }
            /*持久化：批量新增*/
//            lineQcodeService.saveBatch(list);
//            linePasswordService.saveBatch(linePassList);
        }
        /*解析完删除此路径下的文件*/

        file.delete();

        return R.ok().put("totalNum",totalNum);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:lineqcode:info")
    public R info(@PathVariable("id") Integer id){
        LineQcodeEntity lineQcode = lineQcodeService.getById(id);

        return R.ok().put("lineQcode", lineQcode);
    }

    /**
     * 保存
     */
//    @RequestMapping("/save")
//    @RequiresPermissions("sys:lineqcode:save")
//    public R save(@RequestBody String num) throws WriterException, IOException {
//        final String  url="http://127.0.0.1:8080/gongxiangchongdian-admin/uploadImg";
//        System.out.println("数量"+ num);
//        String QR_CodeName = "";
////        WxUtils.getQRCode();
//        int codeNum = Integer.parseInt(num.substring(1,num.length()-1));
//        System.out.println("数量222"+ codeNum);
//        for (int i=1;i<=codeNum;i++) {
//            LineQcodeEntity lineQcode = new LineQcodeEntity();
//            QR_CodeName = RandomUtil.generateString(16);
//            lineQcode.setQcode(QR_CodeName);
//            lineQcode.setQcodeurl(url+"/"+QR_CodeName+".png");
//            lineQcode.setCreatetime(new Date());
//            try {
//                CreateQR_Code(QR_CodeName);
//            }catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            lineQcodeService.save(lineQcode);
//        }
//
//        return R.ok();
//    }


//    public void CreateQR_Code(String QR_CodeName) throws Exception {
//        String storePath="C:\\Users\\Administrator\\Desktop\\data";
//        //图片存放根目录下的子目录
//        String fileName = QR_CodeName;
//        String qrUrl=fileName+".png";
//        String getTokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa8c4555d4bb58d5a&secret=df360519a17e44f2f0a52d7c2b8aea42";
//        JSONObject json = HttpClientUtils.httpRequest(getTokenUrl,"GET",null);
////        JSONObject params = JSONObject.fromObject(HttpClientWeixinUtils.httpRequest(getTokenUrl,"GET",null));
//        String access_token=json.getString("access_token");
//
//        InputStream input = null;
//        FileOutputStream output = null;
//        try {
//            // 从微信获取的流,这个utils就是根据返回mediaId后去流的
//            input = getInputStream(access_token);
//            File folder = new File(storePath);
//            if (!folder.exists()) {
//                folder.mkdirs();
//            }
//            File targetFile = new File(folder, qrUrl);
//            output = new FileOutputStream(targetFile);
//            IOUtils.copy(input, output);
////            fyTeacherService.updateTeacherUrl(teacherUrl,fyTeacher.getId());
//            //上边就是把图片保存到服务器里
//            //下边是数据库的一些操作
//            // 如果数据库有就删除
//        } finally {
//            IOUtils.closeQuietly(input);
//            IOUtils.closeQuietly(output);
//        }
//    }
//
//    public InputStream getInputStream(String access_token) throws Exception {
//        InputStream is = null;
//        String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
//        try {
//            URL url1 = new URL(url);// 创建连接
//            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            connection.setUseCaches(false);
//            connection.setInstanceFollowRedirects(true);
//            connection.setRequestMethod("POST"); // 设置请求方式
//            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
//            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
//            connection.connect();
//            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
//            // 发送请求参数
//            JSONObject paramJson = new JSONObject();
//            paramJson.put("scene", 1);
////            paramJson.put("page", "pages/index/index");
//            paramJson.put("width", 430);
//            paramJson.put("auto_color", true);
//            out.append(paramJson.toString());
//            out.flush();
//            out.close();
//            is = connection.getInputStream();
//            return is;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null; // 自定义错误信息
//    }

    @RequestMapping("/save")
    @RequiresPermissions("sys:lineqcode:save")
    public R save(@RequestBody String num) throws WriterException, IOException {
//        final String  url="http://127.0.0.1:8080/gongxiangchongdian-admin/uploadImg";


        QueryWrapper<LineQcodeEntity> Wrapper = new QueryWrapper<>();
        LineQcodeEntity entity = new LineQcodeEntity();
        Wrapper.orderByAsc("qcode");
        List<LineQcodeEntity> list = lineQcodeService.list(Wrapper);
        int startNum = 1908000000;
        if(list.size()>0){
            String str = list.get(list.size()-1).getQcode().substring(2);
            startNum = Integer.parseInt(str);
        }


        final String  url="https://dyc.ctolab.cn/renren-admin/uploadImg";
        System.out.println("数量"+ num);
        String QR_CodeName = "";
        String localpath = "";

        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        int codeNum = Integer.parseInt(num.substring(1,num.length()-1));
        System.out.println("数量222"+ codeNum);
        for (int i=1;i<=codeNum;i++) {
            LineQcodeEntity lineQcode = new LineQcodeEntity();
//            QR_CodeName = "wd"+RandomUtil.randomTenCount();
            QR_CodeName = "wd"+String.valueOf(startNum+=1);
            lineQcode.setQcode(QR_CodeName);
            localpath = path+"\\"+QR_CodeName+".jpg";
            lineQcode.setQcodeurl(url+"/"+QR_CodeName+".png");
            lineQcode.setCreatetime(new Date());
            try {
                CreateQR_Code(localpath, QR_CodeName);
            }catch (Exception e) {
                e.printStackTrace();
            }

            lineQcodeService.save(lineQcode);
        }

        return R.ok();
    }
    /**
     * 生成二维码
     * @param localpath
     * @throws WriterException
     * @throws IOException
     */
    private void CreateQR_Code(String localpath, String QR_Code) throws WriterException, IOException {
//        String content = " ";
//        String content = "http://127.0.0.1:8080/gongxiangchongdian-admin?o=l55=&&t=wd"+QR_Code;
        String content = "https://dyc.ctolab.cn?code="+QR_Code;
        int width = 300;
        int height = 300;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(localpath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:lineqcode:update")
    public R update(@RequestBody LineQcodeEntity lineQcode){
        ValidatorUtils.validateEntity(lineQcode);
        lineQcodeService.updateById(lineQcode);
        
        return R.ok();
    }

    /**
     * 下载单条
     */
    @RequestMapping("/downLoadCode/{id}")
    @RequiresPermissions("sys:lineqcode:info")
    public R downLoadCode(@PathVariable("id") Integer id){
        LineQcodeEntity lineQcode = lineQcodeService.getById(id);

        return R.ok().put("lineQcode", lineQcode);
    }

    /**
     * 下载所有
     * @param
     * @return
     */
    @RequestMapping("/downLoadAllCode")
    public String downLoadAllCode(){
        String url = "C:\\Users\\Administrator\\Desktop";
//        ValidatorUtils.validateEntity(lineQcode);
        java.util.List<LineQcodeEntity> list = lineQcodeService.list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String[] headers = { "二维码编号"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell1 = row1.createCell(0);
        HSSFRichTextString richString1 =  new HSSFRichTextString("");
        cell1.setCellValue(richString1);


//        HSSFCell cell2 = row1.createCell(1);
//        HSSFRichTextString richString2 =  new HSSFRichTextString(shelvesname);
//        cell2.setCellValue(richString2);
//
//        HSSFCell cell3 = row1.createCell(3);
//        HSSFRichTextString richString3 =  new HSSFRichTextString("补货方式：");
//        cell3.setCellValue(richString3);
//
//        HSSFCell cell4 = row1.createCell(4);
//        HSSFRichTextString richString4 =  new HSSFRichTextString("补至库存上限");
//        cell4.setCellValue(richString4);
//
//        HSSFCell cell5 = row1.createCell(7);
//        HSSFRichTextString richString5 =  new HSSFRichTextString("日期：");
//        cell5.setCellValue(richString5);
//
//        HSSFCell cell6 = row1.createCell(8);
//        HSSFRichTextString richString6 =  new HSSFRichTextString(format.format(new Date()));
//        cell6.setCellValue(richString6);


        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }

        //遍历集合，将每个集合元素对象的每个值填充到单元格中
        for(int i=0;i<list.size();i++){
            LineQcodeEntity entity=list.get(i);
            //从第二行开始填充数据
            row = sheet.createRow(i+2);
            //该集合只记录数量和时间，这两个值来自statisticsModel。如果对象比较复杂，需要额外转换，比如Date类型的日期，int，float类型的数值
            List<String> datas=new ArrayList<>();

            String qcode = entity.getQcode();
//            String barcode = entity.getBarcode();
//            String lowerLimit = entity.getLowerLimit().toString();
//            String upperLimit = entity.getUpperLimit().toString();
//            String stock = entity.getStock().toString();
//            String onshelves = entity.getOnshelves().toString();
//            String buycount = entity.getBuycount().toString();
//            String avgcost = entity.getAvgcost().toString();
//            String totalcost = entity.getTotalcost().toString();
            datas.add(qcode);
//            datas.add(barcode);
//            datas.add(lowerLimit);
//            datas.add(upperLimit);
//            datas.add(stock);
//            datas.add(onshelves);
//            datas.add(buycount);
//            datas.add(avgcost);
//            datas.add(totalcost);
            for (int j=0;j<datas.size();j++) {
                String string=datas.get(j);
                HSSFCell cell = row.createCell(j);
                HSSFRichTextString richString = new HSSFRichTextString(string);
                HSSFFont font3 = workbook.createFont();
                //定义Excel数据颜色，这里设置为蓝色
                font3.setColor(HSSFColor.BLUE.index);
                richString.applyFont(font3);
                cell.setCellValue(richString);
            }

        }
        String message = "";
        File desktopDir = FileSystemView.getFileSystemView()
                .getHomeDirectory();
        try {
//            FileOutputStream fout = new FileOutputStream(url+"/"+"线充二维码"+sdf.format(new Date())+".xls");
            FileOutputStream fout = new FileOutputStream(url+"/"+"线充二维码.xls");
            workbook.write(fout);
            message = url+"/"+"线充二维码.xls成功,请到桌面查找！";
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
            message = "导出失败！";
        }

        return message;
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:lineqcode:delete")
    public R delete(@RequestBody Integer[] ids){
        lineQcodeService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteById")
    public R deleteById(@RequestBody Integer id){
        lineQcodeService.removeById(id);

        return R.ok();
    }
    /**
     * 重置密码
     */
    @RequestMapping("/reSetById")
    public R reSetById(@RequestBody Integer id){

        LineQcodeEntity lineQcode= lineQcodeService.getById(id);

        String password = "";
        IntByReference cnt = new IntByReference(0);//
        byte[] pass = new byte[6];
        Zdmmxencrypt.Clibrary.INSTANTCE.zdmmxencrypt(cnt, 2718793814L,Integer.parseInt(lineQcode.getSn()), 1, pass);

        for (int i = 0; i < pass.length; i++) {
            password += pass[i];
        }
        lineQcode.setCnt(3);
        lineQcode.setPassword(password);
        lineQcodeService.updateById(lineQcode);
        return R.ok();
    }


    /**
     * 下载/批量下载
     */
    @RequestMapping("/downCode")
    public R downCode(@RequestBody Integer[] ids) {
        LineQcodeEntity lineQcode = new LineQcodeEntity();
        for(int i =0;i<ids.length;i++) {
            lineQcode = lineQcodeService.getById(ids[i]);
            String img = lineQcode.getQcodeurl();

            SavePicture(img);
        }
        return R.ok();
    }

    /**
     * 保持图片
     * @param img
     */
    private void SavePicture(String img) {
        URL url1 = null;
        try {
            url1 = new URL(img);
            //获得"Desktop/1.txt",并且不需要前面的"/"
            String imgName=img.substring(img.lastIndexOf("/",img.lastIndexOf("/")));
            //"+1"代表在定位时往后取一位,即去掉"/"
            //"-1"代表以"/"字符定位的位置向前取一位
            //从path.lastIndexOf("/")-1位置开始向前寻找倒数第二个"/"的位置
            DataInputStream dataInputStream = new DataInputStream(url1.openStream());
            File folder = new File(pathDownLoad);
//            if (!folder.exists()) {
//                folder.mkdirs();
//            }
            String imgPath = pathDownLoad + imgName;
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imgPath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                if (pdFile(imgPath)){
                    output.write(buffer, 0, length);
                }
            }
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串
            System.out.println(encode);
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断单个文件
     * @param   sPath    判断单个文件
     * @return 单个文件存在返回true，否则返回false
     */
    public boolean pdFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            flag = true;
        }
        return flag;
    }
}
